<li><a class="reference internal" href="#general-library-questions" id="id3">1 General Library Questions</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-i-find-a-module-or-application-to-perform-task-x" id="id4">1.1 How do I find a module or application to perform task X?</a></li>
<li><a class="reference internal" href="#where-is-the-math-py-socket-py-regex-py-etc-source-file" id="id5">1.2 Where is the math.py (socket.py, regex.py, etc.) source file?</a></li>
<li><a class="reference internal" href="#how-do-i-make-a-python-script-executable-on-unix" id="id6">1.3 How do I make a Python script executable on Unix?</a></li>
<li><a class="reference internal" href="#is-there-a-curses-termcap-package-for-python" id="id7">1.4 Is there a curses/termcap package for Python?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-to-c-s-onexit-in-python" id="id8">1.5 Is there an equivalent to C's onexit() in Python?</a></li>
<li><a class="reference internal" href="#why-don-t-my-signal-handlers-work" id="id9">1.6 Why don't my signal handlers work?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#common-tasks" id="id10">2 Common tasks</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-i-test-a-python-program-or-component" id="id11">2.1 How do I test a Python program or component?</a></li>
<li><a class="reference internal" href="#how-do-i-create-documentation-from-doc-strings" id="id12">2.2 How do I create documentation from doc strings?</a></li>
<li><a class="reference internal" href="#how-do-i-get-a-single-keypress-at-a-time" id="id13">2.3 How do I get a single keypress at a time?</a></li>
<li><a class="reference internal" href="#how-do-i-program-using-threads" id="id15">3.1 How do I program using threads?</a></li>
<li><a class="reference internal" href="#none-of-my-threads-seem-to-run-why" id="id16">3.2 None of my threads seem to run: why?</a></li>
<li><a class="reference internal" href="#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" id="id17">3.3 How do I parcel out work among a bunch of worker threads?</a></li>
<li><a class="reference internal" href="#what-kinds-of-global-value-mutation-are-thread-safe" id="id18">3.4 What kinds of global value mutation are thread-safe?</a></li>
<li><a class="reference internal" href="#can-t-we-get-rid-of-the-global-interpreter-lock" id="id19">3.5 Can't we get rid of the Global Interpreter Lock?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#input-and-output" id="id20">4 Input and Output</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-i-delete-a-file-and-other-file-questions" id="id21">4.1 How do I delete a file? (And other file questions...)</a></li>
<li><a class="reference internal" href="#how-do-i-copy-a-file" id="id22">4.2 How do I copy a file?</a></li>
<li><a class="reference internal" href="#how-do-i-read-or-write-binary-data" id="id23">4.3 How do I read (or write) binary data?</a></li>
<li><a class="reference internal" href="#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" id="id24">4.4 I can't seem to use os.read() on a pipe created with os.popen(); why?</a></li>
<li><a class="reference internal" href="#how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output" id="id25">4.5 How do I run a subprocess with pipes connected to both input and output?</a></li>
<li><a class="reference internal" href="#how-do-i-access-the-serial-rs232-port" id="id26">4.6 How do I access the serial (RS232) port?</a></li>
<li><a class="reference internal" href="#what-www-tools-are-there-for-python" id="id29">5.1 What WWW tools are there for Python?</a></li>
<li><a class="reference internal" href="#how-can-i-mimic-cgi-form-submission-method-post" id="id30">5.2 How can I mimic CGI form submission (METHOD=POST)?</a></li>
<li><a class="reference internal" href="#what-module-should-i-use-to-help-with-generating-html" id="id31">5.3 What module should I use to help with generating HTML?</a></li>
<li><a class="reference internal" href="#how-do-i-send-mail-from-a-python-script" id="id32">5.4 How do I send mail from a Python script?</a></li>
<li><a class="reference internal" href="#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" id="id33">5.5 How do I avoid blocking in the connect() method of a socket?</a></li>
<li><a class="reference internal" href="#are-there-any-interfaces-to-database-packages-in-python" id="id35">6.1 Are there any interfaces to database packages in Python?</a></li>
<li><a class="reference internal" href="#how-do-you-implement-persistent-objects-in-python" id="id36">6.2 How do you implement persistent objects in Python?</a></li>
<li><a class="reference internal" href="#why-is-cpickle-so-slow" id="id37">6.3 Why is cPickle so slow?</a></li>
<li><a class="reference internal" href="#if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come" id="id38">6.4 If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?</a></li>
<li><a class="reference internal" href="#i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data" id="id39">6.5 I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#mathematics-and-numerics" id="id40">7 Mathematics and Numerics</a><ul class="auto-toc">
<li><a class="reference internal" href="#how-do-i-generate-random-numbers-in-python" id="id41">7.1 How do I generate random numbers in Python?</a></li>
<h2><a class="toc-backref" href="#id6">1.3 How do I make a Python script executable on Unix?</a></h2>
<p>You need to do two things: the script file's mode must be executable
and the first line must begin with <tt class="docutils literal"><span class="pre">#!</span></tt> followed by the path of
the Python interpreter.</p>
<p>The first is done by executing <tt class="docutils literal"><span class="pre">chmod</span> <span class="pre">+x</span> <span class="pre">scriptfile</span></tt> or perhaps
<h2><a class="toc-backref" href="#id11">2.1 How do I test a Python program or component?</a></h2>
<p>Python comes with two testing frameworks. The <a class="reference external" href="http://www.python.org/doc/lib/module-doctest.html">doctest module</a> finds examples
in the docstrings for a module and runs them, comparing the output
with the expected output given in the docstring.</p>
<p>The <a class="reference external" href="http://www.python.org/doc/lib/module-unittest.html">unittest module</a> is a fancier
testing framework modelled on Java and Smalltalk testing frameworks.</p>
<p>For testing, it helps to write the program so that it may be easily
tested by using good modular design. Your program should have almost
all functionality encapsulated in either functions or class methods --
and this sometimes has the surprising and delightful effect of making
the program run faster (because local variable accesses are faster
than global accesses). Furthermore the program should avoid depending
on mutating global variables, since this makes testing much more
difficult to do.</p>
<p>The "global main logic" of your program may be as simple
as</p>
<pre class="literal-block">
if __name__=="__main__":
main_logic()
</pre>
<p>at the bottom of the main module of your program.</p>
<p>Once your program is organized as a tractable collection
of functions and class behaviours you should write test
functions that exercise the behaviours. A test suite
can be associated with each module which automates
a sequence of tests. This sounds like a lot of work, but
since Python is so terse and flexible it's surprisingly easy.
You can make coding much more pleasant and fun by
writing your test functions in parallel with the "production
code", since this makes it easy to find bugs and even
design flaws earlier.</p>
<p>"Support modules" that are not intended to be the main module of a
program may include a self-test of the module.</p>
<pre class="literal-block">
if __name__ == "__main__":
self_test()
</pre>
<p>Even programs that interact with complex external interfaces may be
tested when the external interfaces are unavailable by using "fake"
<p>You need the <tt class="docutils literal"><span class="pre">termios</span></tt> and the <tt class="docutils literal"><span class="pre">fcntl</span></tt> module for any of this to work,
and I've only tried it on Linux, though it should work elsewhere.
In this code, characters are read and printed one at a time.</p>
<p><tt class="docutils literal"><span class="pre">termios.tcsetattr()</span></tt> turns off stdin's echoing and disables canonical
mode. <tt class="docutils literal"><span class="pre">fcntl.fnctl()</span></tt> is used to obtain stdin's file descriptor flags
and modify them for non-blocking mode. Since reading stdin when it is
empty results in an <tt class="docutils literal"><span class="pre">IOError</span></tt>, this error is caught and ignored.</p>
<h2><a class="toc-backref" href="#id17">3.3 How do I parcel out work among a bunch of worker threads?</a></h2>
<p>Use the <a class="reference external" href="http://www.python.org/doc/lib/module-Queue.html">Queue module</a> to create a queue
containing a list of jobs. The <tt class="docutils literal"><span class="pre">Queue</span></tt> class maintains a list of
objects with <tt class="docutils literal"><span class="pre">.put(obj)</span></tt> to add an item to the queue and <tt class="docutils literal"><span class="pre">.get()</span></tt>
to return an item. The class will take care of the locking necessary
to ensure that each job is handed out exactly once.</p>
<p>Here's a trivial example:</p>
<pre class="literal-block">
import threading, Queue, time
# The worker thread gets jobs off the queue. When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker ():
print 'Running worker'
time.sleep(0.1)
while True:
try:
arg = q.get(block=False)
except Queue.Empty:
print 'Worker', threading.currentThread(),
print 'queue empty'
break
else:
print 'Worker', threading.currentThread(),
print 'running with argument', arg
time.sleep(0.5)
# Create queue
q = Queue.Queue()
# Start a pool of 5 workers
for i in range(5):
t = threading.Thread(target=worker, name='worker %i' % (i+1))
t.start()
# Begin adding work to the queue
for i in range(50):
q.put(i)
# Give threads time to run
print 'Main thread sleeping'
time.sleep(5)
</pre>
<p>When run, this will produce the following output:</p>
<blockquote>
Running worker
Running worker
Running worker
Running worker
Running worker
Main thread sleeping
Worker <Thread(worker 1, started)> running with argument 0
Worker <Thread(worker 2, started)> running with argument 1
Worker <Thread(worker 3, started)> running with argument 2
Worker <Thread(worker 4, started)> running with argument 3
Worker <Thread(worker 5, started)> running with argument 4
Worker <Thread(worker 1, started)> running with argument 5
...</blockquote>
<p>Consult the module's documentation for more details; the <tt class="docutils literal"><span class="pre">Queue</span></tt>
<h2><a class="toc-backref" href="#id21">4.1 How do I delete a file? (And other file questions...)</a></h2>
<p>Use <tt class="docutils literal"><span class="pre">os.remove(filename)</span></tt> or <tt class="docutils literal"><span class="pre">os.unlink(filename)</span></tt>; for
documentation, see <a class="reference external" href="http://www.python.org/doc/lib/module-posix.html">the POSIX module</a>. The two
functions are identical; <tt class="docutils literal"><span class="pre">unlink()</span></tt> is simply the name of the Unix
system call for this function.</p>
<p>To remove a directory, use <tt class="docutils literal"><span class="pre">os.rmdir()</span></tt>; use <tt class="docutils literal"><span class="pre">os.mkdir()</span></tt> to
create one. <tt class="docutils literal"><span class="pre">os.makedirs(path)</span></tt> will create any intermediate
directories in <tt class="docutils literal"><span class="pre">path</span></tt> that don't exist. <tt class="docutils literal"><span class="pre">os.removedirs(path)</span></tt> will
remove intermediate directories as long as they're empty; if you want
to delete an entire directory tree and its contents, use
<p>To rename a file, use <tt class="docutils literal"><span class="pre">os.rename(old_path,</span> <span class="pre">new_path)</span></tt>.</p>
<p>To truncate a file, open it using <tt class="docutils literal"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">open(filename,</span> <span class="pre">"r+")</span></tt>, and use
<tt class="docutils literal"><span class="pre">f.truncate(offset)</span></tt>; offset defaults to the current seek position.
There's also <tt class="docutils literal"><span class="pre">`os.ftruncate(fd,</span> <span class="pre">offset)</span></tt> for files opened with <tt class="docutils literal"><span class="pre">os.open()</span></tt>,
where <tt class="docutils literal"><span class="pre">fd</span></tt> is the file descriptor (a small integer).</p>
<p>The <tt class="docutils literal"><span class="pre">shutil</span></tt> module also contains a number of functions to work on files
including <tt class="docutils literal"><span class="pre">copyfile</span></tt>, <tt class="docutils literal"><span class="pre">copytree</span></tt>, and <tt class="docutils literal"><span class="pre">rmtree</span></tt>.</p>
</div>
<div class="section" id="how-do-i-copy-a-file">
<h2><a class="toc-backref" href="#id22">4.2 How do I copy a file?</a></h2>
<p>The <tt class="docutils literal"><span class="pre">shutil</span></tt> module contains a <tt class="docutils literal"><span class="pre">copyfile()</span></tt> function. Note that
on MacOS 9 it doesn't copy the resource fork and Finder info.</p>
<h2><a class="toc-backref" href="#id23">4.3 How do I read (or write) binary data?</a></h2>
<p>or complex data formats, it's best to use <a class="reference external" href="http://www.python.org/doc/lib/module-struct.html">the struct module</a>. It allows you
to take a string containing binary data (usually numbers) and convert
it to Python objects; and vice versa.</p>
<p>For example, the following code reads two 2-byte integers
and one 4-byte integer in big-endian format from a file:</p>
<pre class="literal-block">
import struct
f = open(filename, "rb") # Open in binary mode for portability
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)
</pre>
<p>The '>' in the format string forces big-endian data; the letter
'h' reads one "short integer" (2 bytes), and 'l' reads one
"long integer" (4 bytes) from the string.</p>
<p>For data that is more regular (e.g. a homogeneous list of ints or
thefloats), you can also use <a class="reference external" href="http://www.python.org/doc/lib/module-array.html">the array module</a>.</p>
<h2><a class="toc-backref" href="#id24">4.4 I can't seem to use os.read() on a pipe created with os.popen(); why?</a></h2>
<p><tt class="docutils literal"><span class="pre">os.read()</span></tt> is a low-level function which takes a file descriptor, a
small integer representing the opened file. <tt class="docutils literal"><span class="pre">os.popen()</span></tt> creates a
high-level file object, the same type returned by the builtin
<tt class="docutils literal"><span class="pre">open()</span></tt> function. Thus, to read n bytes from a pipe p created with
<tt class="docutils literal"><span class="pre">os.popen()</span></tt>, you need to use <tt class="docutils literal"><span class="pre">p.read(n)</span></tt>.</p>
<h2><a class="toc-backref" href="#id25">4.5 How do I run a subprocess with pipes connected to both input and output?</a></h2>
<p>Use <a class="reference external" href="http://www.python.org/doc/lib/module-popen2.html">the popen2 module</a>. For example:</p>
<pre class="literal-block">
import popen2
fromchild, tochild = popen2.popen2("command")
tochild.write("input\n")
tochild.flush()
output = fromchild.readline()
</pre>
<p>Warning: in general it is unwise to do this because you can easily
cause a deadlock where your process is blocked waiting for output from
the child while the child is blocked waiting for input from you. This
can be caused because the parent expects the child to output more text
than it does, or it can be caused by data being stuck in stdio buffers
due to lack of flushing. The Python parent can of course explicitly
flush the data it sends to the child before it reads any output, but
if the child is a naive C program it may have been written to never
explicitly flush its output, even if it is interactive, since flushing
is normally automatic.</p>
<p>Note that a deadlock is also possible if you use <tt class="docutils literal"><span class="pre">popen3</span></tt> to read
stdout and stderr. If one of the two is too large for the internal
buffer (increasing the buffer size does not help) and you <tt class="docutils literal"><span class="pre">read()</span></tt>
the other one first, there is a deadlock, too.</p>
<p>Note on a bug in popen2: unless your program calls <tt class="docutils literal"><span class="pre">wait()</span></tt>
or <tt class="docutils literal"><span class="pre">waitpid()</span></tt>, finished child processes are never removed,
and eventually calls to popen2 will fail because of a limit on
the number of child processes. Calling <tt class="docutils literal"><span class="pre">os.waitpid</span></tt> with the
<tt class="docutils literal"><span class="pre">os.WNOHANG</span></tt> option can prevent this; a good place to insert such
a call would be before calling <tt class="docutils literal"><span class="pre">popen2</span></tt> again.</p>
<p>In many cases, all you really need is to run some data through a
command and get the result back. Unless the amount of data is very
large, the easiest way to do this is to write it to a temporary file
and run the command with that temporary file as input. The <a class="reference external" href="http://www.python.org/doc/lib/module-tempfile.html">standard
module tempfile</a>
exports a <tt class="docutils literal"><span class="pre">mktemp()</span></tt> function to generate unique temporary file names.</p>
<pre class="literal-block">
import tempfile
import os
class Popen3:
"""
This is a deadlock-safe version of popen that returns
an object with errorlevel, out (a string) and err (a string).
<h2><a class="toc-backref" href="#id29">5.1 What WWW tools are there for Python?</a></h2>
<p>See the chapters titled <a class="reference external" href="http://www.python.org/doc/lib/internet.html">"Internet Protocols and Support"</a> and <a class="reference external" href="http://www.python.org/doc/lib/netdata.html">"Internet Data
Handling"</a> in the
Library Reference Manual. Python has many modules that will help you
build server-side and client-side web systems.</p>
<p>A summary of available frameworks is maintained by Paul Boddie at
<h2><a class="toc-backref" href="#id33">5.5 How do I avoid blocking in the connect() method of a socket?</a></h2>
<p>The select module is commonly used to help with asynchronous
I/O on sockets.</p>
<p>To prevent the TCP connect from blocking, you can set the socket to
non-blocking mode. Then when you do the <tt class="docutils literal"><span class="pre">connect()</span></tt>, you will
either connect immediately (unlikely) or get an exception that
contains the error number as <tt class="docutils literal"><span class="pre">.errno</span></tt>. <tt class="docutils literal"><span class="pre">errno.EINPROGRESS</span></tt>
indicates that the connection is in progress, but hasn't finished yet.
Different OSes will return different values, so you're going to have
to check what's returned on your system.</p>
<p>You can use the <tt class="docutils literal"><span class="pre">connect_ex()</span></tt> method to avoid creating an
exception. It will just return the errno value. To poll, you can
call <tt class="docutils literal"><span class="pre">connect_ex()</span></tt> again later -- 0 or <tt class="docutils literal"><span class="pre">errno.EISCONN</span></tt> indicate
that you're connected -- or you can pass this socket to select to
<h2><a class="toc-backref" href="#id35">6.1 Are there any interfaces to database packages in Python?</a></h2>
<p>Yes.</p>
<p>Python 2.3 includes the <tt class="docutils literal"><span class="pre">bsddb</span></tt> package which provides an interface
to the <a class="reference external" href="http://www.python.org/doc/lib/module-bsddb.html">BerkeleyDB</a> library.
Interfaces to disk-based hashes such as <a class="reference external" href="http://www.python.org/doc/lib/module-dbm.html">DBM</a> and <a class="reference external" href="http://www.python.org/doc/lib/module-gdbm.html">GDBM</a> are also included
with standard Python.</p>
<p>Support for most relational databases is available. See the <a class="reference external" href="http://www.python.org/topics/database">Database
<h2><a class="toc-backref" href="#id36">6.2 How do you implement persistent objects in Python?</a></h2>
<p>The <a class="reference external" href="http://www.python.org/doc/lib/module-pickle.html">pickle library module</a> solves this in a
very general way (though you still can't store things like open files,
sockets or windows), and the <a class="reference external" href="http://www.python.org/doc/lib/module-shelve.html">shelve library module</a> uses pickle and
(g)dbm to create persistent mappings containing arbitrary Python
<h2><a class="toc-backref" href="#id39">6.5 I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?</a></h2>
<p>Don't panic! Your data is probably intact. The most frequent cause
for the error is that you tried to open an earlier Berkeley DB file
with a later version of the Berkeley DB library.</p>
<p>Many Linux systems now have all three versions of Berkeley DB
available. If you are migrating from version 1 to a newer version use
db_dump185 to dump a plain text version of the database.
If you are migrating from version 2 to version 3 use db2_dump to create
a plain text version of the database. In either case, use db_load to
create a new native database for the latest version installed on your
computer. If you have version 3 of Berkeley DB installed, you should
be able to use db2_load to create a native version 2 database.</p>
<p>You should move away from Berkeley DB version 1 files because
the hash file code contains known bugs that can corrupt your data.</p>
<h2><a class="toc-backref" href="#id41">7.1 How do I generate random numbers in Python?</a></h2>
<p>The <a class="reference external" href="http://www.python.org/doc/lib/module-random.html">standard module random</a> implements a random number
generator. Usage is simple:</p>
<pre class="literal-block">
import random
random.random()
</pre>
<p>This returns a random floating point number in the range [0, 1).</p>
<p>There are also many other specialized generators in this module, such
as:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">randrange(a,</span> <span class="pre">b)</span></tt> chooses an integer in the range [a, b).</li>
<li><tt class="docutils literal"><span class="pre">uniform(a,</span> <span class="pre">b)</span></tt> chooses a floating point number in the range [a, b).</li>
<li><tt class="docutils literal"><span class="pre">normalvariate(mean,</span> <span class="pre">sdev)</span></tt> samples the normal (Gaussian) distribution.</li>
</ul>
<p>Some higher-level functions operate on sequences directly, such as:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">choice(S)</span></tt> chooses random element from a given sequence</li>
<li><tt class="docutils literal"><span class="pre">shuffle(L)</span></tt> shuffles a list in-place, i.e. permutes it randomly</li>
</ul>
<p>There's also a <tt class="docutils literal"><span class="pre">Random</span></tt> class you can instantiate
to create independent multiple random number generators.</p>